<?php

namespace wxpay;

class Tixian
{

    public $appid = 'wxde7c4c1de695c4ca';//appid
    public $mch_id= 1678233381;//商户号id
    public $cert_pem= '';//商户证书（绝对路径）
    public $key_pem= '';//商户密匙（绝对路径）


    /***
     *主函数（微信提现）
     **/
    public function WechatTransfer($request_params)
    {
//        $request_params = [
//            'amount'=>100,
//            'trans_no'=>'plfk2020042013',
//            'desc'=>'测试接口',
//            'openid'=>'dsadsadasd',
//        ];
        $xml_data = $this->buildParams($request_params);//构建参数
        $url = 'https://api.mch.weixin.qq.com/v3/transfer/batches';//微信提现接口
        $xml_datas = json_encode($xml_data);
        $token = $this->getToken($url,'POST',time(),$xml_datas);//获取header Token认证

        $res_xml = $this->https_request($url,$xml_datas,$token);//请求
        $resArr = json_decode($res_xml,true);//请求返回
        return $resArr;
    }

    /**
     *请求接口参数获取
     */
    protected function getSelfParams(array $request_params){
        $total_fee = (int)bcmul($request_params['amount'], 100, 0);
        $self_params = [
            'appid'      => $this->appid,
            'out_batch_no'=>$request_params['trans_no']??'',
            'batch_name'  =>'用户提现'??'',
            'batch_remark'=>$request_params['desc'].date('Y-m-d H:i:s')??'',
            'total_amount'=>$total_fee,
            'total_num'=>1,
            'transfer_detail_list'=>[
                [
                    //单次转账一人，多人添加数组即可
                    'out_detail_no'=>$request_params['trans_no'].'1'??'',
                    'transfer_remark'=>$request_params['desc']??'',
                    'transfer_amount'=>$total_fee,
                    'openid'         => $request_params['openid'] ?? ''
                ]
            ],
        ];
        return $self_params;
    }
    /***
     **构建参数
     */
    protected function buildParams(array $request_params = []){
        $params = [
            'appid'      => $this->appid,//appid
            'mch_id'     =>  $this->mch_id,//商户号
        ];
        if (!empty($request_params)) {
            $self_params = $this->getSelfParams($request_params);//获取参数
            if (is_array($self_params) && !empty($self_params)) {
                $params = array_merge($params, $self_params);//合并参数
            }
        }
        $params = $this->paraFilter($params);//过滤参数
        $params = $this->arraySort($params);//参数排序
        return $params;

    }

    /**
     *获取认证
     */
    public function getToken($url,$http_method,$timestamp,$body='')
    {
        // $url = 'https://api.mch.weixin.qq.com/v3/certificates';
        $url_parts   = parse_url($url);//获取请求的绝对URL
        $nonce       = $timestamp . rand('10000', '99999');//请求随机串
        $stream_opts = [
            "ssl" => [
                "verify_peer"=>false,
                "verify_peer_name"=>false,
            ]
        ];

        $p = "file://".str_replace('\\', '/', dirname(dirname(dirname(__DIR__))));
        $this->cert_pem =$p."/server/certificate/apiclient_cert.pem";
        $this->key_pem = $p."/server/certificate/apiclient_key.pem";


        $apiclient_cert_path = $this->cert_pem;//商户证书
        $apiclient_key_path  = $this->key_pem;//商户密匙
        $apiclient_cert_arr = openssl_x509_parse(file_get_contents($apiclient_cert_path,false, stream_context_create($stream_opts)));
        $serial_no          = $apiclient_cert_arr['serialNumberHex'];//证书序列号(忽略)
        $mch_private_key    = file_get_contents($apiclient_key_path,false, stream_context_create($stream_opts));//密钥
        $merchant_id = $this->mch_id;//商户id
        $canonical_url = ($url_parts['path'] . (!empty($url_parts['query']) ? "?${url_parts['query']}" : ""));
        $message = $http_method."\n".
            $canonical_url."\n".
            $timestamp."\n".
            $nonce."\n".
            $body."\n";
        openssl_sign($message, $raw_sign, $mch_private_key, 'sha256WithRSAEncryption');
        $sign = base64_encode($raw_sign);//签名
        $schema = 'WECHATPAY2-SHA256-RSA2048';
        $token = sprintf('mchid="%s",nonce_str="%s",timestamp="%d",serial_no="%s",signature="%s"',
            $merchant_id, $nonce, $timestamp, $serial_no, $sign);//微信返回token
        return $token;
    }

    public function paraFilter($para)
    {
        $paraFilter = [];
        foreach ($para as $key => $val) {
            if ($val === '' || $val === null) {
                continue;
            }
            if (!is_array($para[$key])) {
                if (!is_numeric($para[$key])){
                    $para[$key] = is_bool($para[$key]) ? $para[$key] : trim($para[$key]);
                }
            }

            $paraFilter[$key] = $para[$key];
        }

        return $paraFilter;
    }

    public function arraySort(array $param)
    {
        ksort($param);
        reset($param);

        return $param;
    }


    /**
     *请求接口
     */
    function https_request($url,$data = null,$token=''){
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, (string)$url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        if (!empty($data)){
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        //添加请求头
        $headers = [
            'Authorization:WECHATPAY2-SHA256-RSA2048 '.$token,
            'Accept: application/json',
            'Content-Type: application/json; charset=utf-8',
            'User-Agent:Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36',
        ];
        if(!empty($headers)){
            curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        }
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }


}